import React, { Component, Fragment } from 'react'
import ReactDOM from 'react-dom'
import { createPortal } from 'react-dom'
import './index.scss'
let timer = null
export default class Message extends Component {
  constructor() {
    const doc = window.document
    this.node = doc.createElement('div')
    doc.body.appendChild(this.node)
  }
  static info(msg = 'info', timeout = 2000) {
    init()
    setTime(timeout)
    ReactDOM.render(
      <div className="toast info">
        <img
          className="message-img"
          src={require('../../image/icon/tanhao_h.png')}
        />
        <span>{msg}</span>
      </div>,
      document.getElementById('toast')
    )
  }
  static success(msg = 'success', timeout = 2000) {
    init()
    setTime(timeout)
    ReactDOM.render(
      <div className="toast success">
        <img
          className="message-img"
          src={require('../../image/icon/tanhao_b.png')}
        />
        <span>{msg}</span>
      </div>,
      document.getElementById('toast')
    )
  }
  static warning(msg = 'warning', timeout = 2000) {
    init()
    setTime(timeout)
    ReactDOM.render(
      <div className="toast warning">
        <img
          className="message-img"
          src={require('../../image/icon/tanhao_b.png')}
        />
        <span>{msg}</span>
      </div>,
      document.getElementById('toast')
    )
  }
  static error(msg = 'error', timeout = 2000) {
    init()
    setTime(timeout)
    ReactDOM.render(
      <div className="toast error">
        <img
          className="message-img"
          src={require('../../image/icon/tanhao_b.png')}
        />
        <span>{msg}</span>
      </div>,
      document.getElementById('toast')
    )
  }
}

function init() {
  clearTimeout(timer)
  let doc = document.getElementById('toast')
  if (!doc) {
    let div = document.createElement('div')
    div.setAttribute('id', 'toast')

    window.document.body.appendChild(div)
  }
}
function setTime(timeout) {
  timer = setTimeout(() => {
    let div = document.getElementById('toast')
    if (div) {
      window.document.body.removeChild(div)
    }
  }, timeout)
}
